<template>
  <view class="container">
    <u-form :model="form" ref="uForm" :rules="rules" label-width="120">
		<view class="form-section">
		<text class="section-title">成交信息</text>
		<u-form-item label="成交产品" prop="productId" required>
		  <uni-data-select
		  	 collection="mydb-product-list"
		  	 field="_id as value, title as text"
		  	 v-model="form.productId"
		   />
		</u-form-item>
		
		<u-form-item label="成交金额(万)" prop="limit" required>
		  <u-input v-model="form.limit" placeholder="请输入贷款额度" maxlength="11" />
		</u-form-item>
		<u-form-item label="合同期限(月)" prop="loanPeriod" required>
		  <uni-data-checkbox v-model="form.loanPeriod" :localdata="loanPeriodOptions"></uni-data-checkbox>
		</u-form-item>
		<u-form-item label="关联人" prop="belongTo" required>
			<uni-data-select
				 collection="uni-id-users"
				 field="_id as value, nickname as text"
				 v-model="form.belongTo"
			 />
		</u-form-item>
		<u-form-item label="备注信息" prop="remark" required>
		  <u-input v-model="form.remark" placeholder="请输入备注信息" />
		</u-form-item>
		 </view>
      <!-- 合同资料上传 -->
      <view class="form-section">
        <text class="section-title">合同资料</text>
        <u-form-item label="成交合同上传" prop="agreementDocs">
          <uni-file-picker
            v-model="form.agreementDocs"
            :limit="4"
          ></uni-file-picker>
        </u-form-item>
      </view>
      <!-- 保存按钮 -->
      <view class="button-group">
        <u-button type="primary" @click="submitForm" :loading="uploading">
          {{ uploading ? '保存中...' : '保存' }}
        </u-button>
        <u-button @click="navigateBack">返回</u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
import { store } from '@/uni_modules/uni-id-pages/common/store.js'
const db = uniCloud.database()
const Odb=uniCloud.importObject('mydb-customer')
let eventChannel=null
export default {
  data() {
    return {
      customerId: null,
      customerName: '',
      form: {
		productId:'',
        agreementDocs: [],
        limit: '',
        loanPeriod: '',
		remark:'',
		belongTo:''
      },
	  loanPeriodOptions:[],
      rules: {
      },
      uploading: false,
    }
  },
  computed: {
    userInfo() {
      return store.userInfo
    }
  },
  onLoad(options) {
    if (options.id) {
      this.customerId = options.id
      this.loadCustomerData()
      this.loadUploadedFiles()
	  this.loadOptions()
    }
  },
  onReady() {
  		//onReady 为uni-app支持的生命周期之一
      	this.$refs.uForm.setRules(this.rules)
  },
  methods: {
	  loadOptions(){
	  	Odb.getOptions().then((res)=>{
	  		for (var key in res) {
	  			if (res.hasOwnProperty(key) && this[key]) {
	  				this[key] = res[key]
	  			}
	  		}
	  	})
	  },
    // 加载客户基本信息
    async loadCustomerData() {
      try {
        const res = await db.collection('mydb-customer').doc(this.customerId).get()
        if (res.result.data.length > 0) {
          this.customerName = res.result.data[0].name
        }
      } catch (error) {
        console.error('加载客户数据失败：', error)
        uni.showToast({ title: '加载客户数据失败', icon: 'none' })
      }
    },

    // 加载已上传的文件信息
    async loadUploadedFiles() {
      try {
        const res = await db.collection('mydb-customer-deal').where({ customerId: this.customerId }).get()
        if (res.result.data.length > 0) {
          const customerData = res.result.data[0]
          this.form = customerData
        }
      } catch (error) {
        console.error('加载已上传文件信息失败：', error)
        uni.showToast({ title: '加载信息失败', icon: 'none' })
      }
    },

  
    // 提交表单
    async submitForm() {
      try {
   
        this.uploading = true
        // 准备要保存的数据
        const updateData = {
          customerId: this.customerId,
          ...this.form,
          lastUpdateBy: this.userInfo._id,
          updateTime: Date.now()
        }

        // 查找是否存在该客户的记录
        const existingRecord = await db.collection('mydb-customer-deal').where({ customerId: this.customerId }).get()

        if (existingRecord.result.data.length > 0) {
          // 更新现有记录
          await db.collection('mydb-customer-deal').doc(existingRecord.result.data[0]._id).update(updateData)
        } else {
          // 创建新记录
          await db.collection('mydb-customer-deal').add(updateData)
        }

        uni.showToast({ title: '保存成功' })
		setTimeout(()=>{
			uni.navigateBack()
		},1000)
      } catch (error) {
        console.error('提交表单失败：', error)
        uni.showToast({ title: `保存失败：${error.message}`, icon: 'none' })
      } finally {
        this.uploading = false
      }
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
  border-left: 6rpx solid #1989fa;
  padding-left: 15rpx;
}

.note-input {
  margin-top: 10rpx;
  border: 1px solid #e4e7ed;
  border-radius: 6rpx;
  padding: 0 20rpx;
}

.button-group {
  margin-top: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 调整uni-file-picker的样式 */
.uni-file-picker {
  margin-top: 10rpx;
}
</style>